package signup.domain;

import java.util.List;

import org.springframework.orm.jpa.support.JpaDaoSupport;

public class VolunteerServiceImpl extends JpaDaoSupport implements VolunteerService {
	
	public VolunteerServiceImpl() {
		super();
	}

	public void fillPositionTimeSlot(Position position, TimeSlot timeSlot,
			Users user) {
		
		if (timeSlot != null){
			TimeSlotService ts = new TimeSlotService();
			ts.addUser(timeSlot, user);
		}else {
			PositionService ps = new PositionService();
			ps.addUser(position, user);
		}
	}

    @SuppressWarnings("unchecked")
	public List<Position> getEventPositions(Event event) {

		 return getJpaTemplate().find(
	                "select e.positions from Event e where e = ?", event);
	}

    @SuppressWarnings("unchecked")
	public List<Event> getEvents() {
		
		 return getJpaTemplate().find(
	                "from Event e where (e.StartDate > current_date() " +
	                "or e.StartDate = current_date() and e.StartTime > current_time())");
	}

    @SuppressWarnings("unchecked")
	public List<TimeSlot> getOpenPositionTimeSlots(Position position) {
    	return getJpaTemplate().find(
	                "select t from TimeSlot t where t.position = ?" +
	                "and size(t.users) < t.numberOfVolunteers ", position);
	}

    @SuppressWarnings("unchecked")
	public List getFilledPositionsAndTimeSlots(Event event){
		return getJpaTemplate().find(
                "select p, t from TimeSlot t, Position p, Event e where e = ? and (" +
                "(size(p.users) >= p.numberOfVolunteers and p in elements(e.positions)) or " +
                "(size(t.users) >= t.numberOfVolunteers and t.position in elements(e.positions)))", event);
		
	}
    
    @SuppressWarnings("unchecked")
	public List<Users> getVolunteers(Event event) {
		return getJpaTemplate().find(
	                "select u from Users u, Event e, TimeSlot t, Position p where e = ? and ((p.event = " +
	                "e and u in elements(p.users)) " +
	                "or (t.position in elements(e.positions) and u in elements(t.users)))", event);
	}

}
